<?php
namespace App\Http\Controllers;

use App\Http\Requests\ProjectStatisticRequest;
use App\Models\ActivityProject;
use App\Models\Project;
use App\Models\RoadShowApply;
use Illuminate\Http\Request;
use \Excel;

class ProjectStatisticController extends CommonController
{

    /**
     * 获取路演统计页面
     */
    public function getRoadshow()
    {
        return view('projectstatistic.roadshow');
    }

    /**
     * 获取项目统计页面
     */
    public function getIndex()
    {
        $total = Project::count();

        return view('projectstatistic.index')->with('total', $total);
    }

    /**
     * 获取数据查询页面
     */
    public function getQuery()
    {

        return view('projectstatistic.query');
    }

    /**
     *ajax获取用户日项目发布数据
     */
    public function getDayPub()
    {
        $day = 24 * 3600;
        $today_zero = strtotime('today');
        //获取今天差几个小时
        $rest = sprintf("%.2f", (24 - (time() - $today_zero) / 3600));

        $date = array();
        //获取前31天的每天凌晨的时间戳,过去的时间排在前面
        $stamps = array();
        for ($i = 30; $i >= 0; $i--) {
            $stamps[] = $today_zero - $i * $day;
            $i > 0 && $date[] = date('m-d', strtotime(-$i . " day"));
        }

        $counts = array();
        for ($i = 1; $i < 31; $i++) {
            //获取前三十天的发布数据，过去的数据放在前面
            $counts[] = Project::whereBetween('created_at', [$stamps[$i - 1], $stamps[$i]])->where('status', '!=', -1)->count();
        }

        $counts[] = Project::whereBetween('created_at', [$today_zero, time()])->where('status', '!=', -1)->count();
        $date[] = '今天差' . $rest . '小时';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

        echo json_encode($arr);
    }

    /**
     *ajax获取用户周项目发布数据
     */
    public function getWeekPub()
    {
        //获取本工作周还剩下几天
        $rest = (6 - date('w')) % 7;
        $rest == 0 && $rest = 7;

        //获取上周六凌晨时间戳
        $thisSta = strtotime('today') - (7 - $rest) * 24 * 3600;

        // 定义一周的时间戳
        $week = 7 * 24 * 3600;

        //获取前30周的每周一凌晨的时间戳,从前往后排
        $stamps = array();
        $date = array();

        for ($i = 30; $i >= 0; $i--) {
            $stamps[] = $thisSta - $i * $week;
            $i > 0 && $date[] = '前' . ($i) . '周';
        }

        $counts = array();
        for ($i = 1; $i < 31; $i++) {
            $counts[] = Project::whereBetween('created_at', [$stamps[$i - 1], $stamps[$i]])->where('status', '!=', -1)->count();
        }
        $counts[] = Project::whereBetween('created_at', [$thisSta, time()])->where('status', '!=', -1)->count();
        $date[] = '本周差' . $rest . '天';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

        echo json_encode($arr);
    }

    /**
     *ajax获取用户月项目发布数据
     */
    public function getMonthPub()
    {
        //获取本月还剩下多少天
        $rest = date('t') - date('j') + 1;
        //获取本月1号凌晨的时间戳
        $thisMonth = strtotime(date('Y-m-01'));
        //获取过去十三个月的，每个月1号凌晨的时间戳，从前往后
        $m = date('m');
        $y = date('Y');
        $stamps = array();
        for ($i = 0; $i < 13; $i++) {
            $newM = $m - $i;
            if ($newM <= 0) {
                $newM += 12;
                $y = $y - 1;
            }
            $stamps[] = strtotime($y . '-' . $newM . '-01');
            $y = date('Y');
        }

        $counts = array();
        for ($i = 12; $i > 0; $i--) {
            //获取前12个月的发布数据，过去的数据放在前面
            $counts[] = Project::whereBetween('created_at', [$stamps[$i], $stamps[$i - 1]])->where('status', '!=', -1)->count();
        }

        $date = array();
        for ($i = 12; $i > 0; $i--) {
            //获取前12个月的文字表述，过去的表述放在前面
            $date[] = $m - $i < 1 ? '去年' . ($m - $i + 12) . '月' : $m - $i . '月';
        }

        $counts[] = Project::whereBetween('created_at', [$thisMonth, time()])->where('status', '!=', -1)->count();
        $date[] = '本月差' . $rest . '天';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

        echo json_encode($arr);
    }

    /**
     * 以天为单位统计路演项目数
     */
    public function getDayShow()
    {
//        $day = 24 * 3600;
//        $today_zero = strtotime('today');
//        //获取今天差几个小时
//        $rest = sprintf("%.2f", (24 - (time() - $today_zero) / 3600));
//
//        $date = array();
//        //获取前31天的每天凌晨的时间戳,过去的时间排在前面
//        $stamps = array();
//        for ($i = 30; $i >= 0; $i--) {
//            $stamps[] = $today_zero - $i * $day;
//            $i > 0 && $date[] = date('m-d', strtotime(-$i . " day"));
//        }
//
//        $counts = array();
//        for ($i = 1; $i < 31; $i++) {
//            //获取前三十天的发布数据，过去的数据放在前面
//            $counts[] = ActivityProject::whereBetween('created_at', [$stamps[$i - 1], $stamps[$i]])->count();
//        }
//
//        $counts[] = ActivityProject::whereBetween('created_at', [$today_zero, time()])->count();
//        $date[] = '今天差' . $rest . '小时';
//
//        $arr = [];
//        foreach ($date as $k => $i) {
//            $arr[] = array($i, $counts[$k]);
//        }
//
//        echo json_encode($arr);
        $day = 24 * 3600;
        $today_zero = strtotime('today');
        //获取今天差几个小时
        $rest = sprintf("%.2f", (24 - (time() - $today_zero) / 3600));

        $date = array();
        //获取前31天的每天凌晨的时间戳,过去的时间排在前面
        $stamps = array();
        for ($i = 30; $i >= 0; $i--) {
            $stamps[] = $today_zero - $i * $day;
            $i > 0 && $date[] = date('m-d', strtotime(-$i . " day"));
        }

        $counts = array();
        for ($i = 1; $i < 31; $i++) {
            //获取前三十天的路演成功数据
            $success = ActivityProject::whereBetween('created_at', [$stamps[$i - 1], $stamps[$i]])->count();
            //获取前三十天的项目路演申请数
            $apply = RoadshowApply::whereBetween('created_at', [$stamps[$i - 1], $stamps[$i]])->count();
            $result = array('success' => $success, 'apply' => $apply);
            $counts[] = $result;
        }

        $today_success = ActivityProject::whereBetween('created_at', [$today_zero, time()])->count();
        $today_apply = RoadshowApply::whereBetween('created_at', [$today_zero, time()])->count();
        $today_result = array('success' => $today_success, 'apply' => $today_apply);
        $counts[] = $today_result;
        $date[] = '今天差' . $rest . '小时';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }
//        dd($arr);

        echo json_encode($arr);
    }

    /**
     * 以周为单位获取路演项目数
     */
    public function getWeekShow()
    {
//        //获取本周还剩下几天
//        $rest = (8 - date('w')) % 7;
//        $rest == 0 && $rest = 7;
//
//        //获取本周一凌晨时间戳
//        $thisMonday = strtotime('today') - (7 - $rest) * 24 * 3600;
//
//        // 定义一周的时间戳
//        $week = 7 * 24 * 3600;
//
//        //获取前30周的每周一凌晨的时间戳,从前往后排
//        $stamps = array();
//        $date = array();
//
//        for ($i = 30; $i >= 0; $i--) {
//            $stamps[] = $thisMonday - $i * $week;
//            $i > 0 && $date[] = '前' . ($i) . '周';
//        }
//
//        $counts = array();
//        for ($i = 1; $i < 31; $i++) {
//            $counts[] = ActivityProject::whereBetween('created_at', [$stamps[$i - 1], $stamps[$i]])->count();
//        }
//        $counts[] = ActivityProject::whereBetween('created_at', [$thisMonday, time()])->count();
//        $date[] = '本周差' . $rest . '天';
//
//        $arr = [];
//        foreach ($date as $k => $i) {
//            $arr[] = array($i, $counts[$k]);
//        }
//
//        echo json_encode($arr);

        //获取本工作周还剩下几天
        $rest = (6 - date('w')) % 7;
        $rest == 0 && $rest = 7;

        //获取上周六凌晨时间戳
        $thisSta = strtotime('today') - (7 - $rest) * 24 * 3600;

        // 定义一周的时间戳
        $week = 7 * 24 * 3600;

        //获取前30周的每周一凌晨的时间戳,从前往后排
        $stamps = array();
        $date = array();

        for ($i = 30; $i >= 0; $i--) {
            $stamps[] = $thisSta - $i * $week;
            $i > 0 && $date[] = '前' . ($i) . '周';
        }

        $counts = array();
        for ($i = 1; $i < 31; $i++) {
            //获取前三十周的项目路演成功数
            $success = ActivityProject::whereBetween('created_at', [$stamps[$i - 1], $stamps[$i]])->count();
            //获取前三十周的项目路演申请数
            $apply = RoadshowApply::whereBetween('created_at', [$stamps[$i - 1], $stamps[$i]])->count();
            $result = array('success' => $success, 'apply' => $apply);
            $counts[] = $result;
        }
        $today_success = ActivityProject::whereBetween('created_at', [$thisSta, time()])->count();
        $today_apply = RoadshowApply::whereBetween('created_at', [$thisSta, time()])->count();
        $today_result = array('success' => $today_success, 'apply' => $today_apply);
        $counts[] = $today_result;
        $date[] = '本周差' . $rest . '天';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

//        dd($arr);
        echo json_encode($arr);
    }

    /**
     * 以月为单位获取路演项目数
     */
    public function getMonthShow()
    {
        //获取本月还剩下多少天
        $rest = date('t') - date('j') + 1;
        //获取本月1号凌晨的时间戳
        $thisMonth = strtotime(date('Y-m-01'));
        //获取过去十三个月的，每个月1号凌晨的时间戳，从前往后
        $m = date('m');
        $y = date('Y');
        $stamps = array();
        for ($i = 0; $i < 13; $i++) {
            $newM = $m - $i;
            if ($newM <= 0) {
                $newM += 12;
                $y = $y - 1;
            }
            $stamps[] = strtotime($y . '-' . $newM . '-01');
            $y = date('Y');
        }

        $counts = array();
        for ($i = 12; $i > 0; $i--) {
            //获取前12个月的发布数据，过去的数据放在前面
            $success = ActivityProject::whereBetween('created_at', [$stamps[$i], $stamps[$i - 1]])->count();
            //获取前三十周的项目路演申请数
            $apply = RoadshowApply::whereBetween('created_at', [$stamps[$i], $stamps[$i - 1]])->count();
            $result = array('success' => $success, 'apply' => $apply);
            $counts[] = $result;
        }

        $date = array();
        for ($i = 12; $i > 0; $i--) {
            //获取前12个月的文字表述，过去的表述放在前面
            $date[] = $m - $i < 1 ? '去年' . ($m - $i + 12) . '月' : $m - $i . '月';
        }

        $today_success = ActivityProject::whereBetween('created_at', [$thisMonth, time()])->count();
        $today_apply = RoadshowApply::whereBetween('created_at', [$thisMonth, time()])->count();
        $today_result = array('success' => $today_success, 'apply' => $today_apply);
        $counts[] = $today_result;
        $date[] = '本月差' . $rest . '天';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

        echo json_encode($arr);
    }

    /**
     * 异步获取数据
     */
    public function postFind(ProjectStatisticRequest $request)
    {
        $data = $request->input();
        $data['end_time'] = strtotime($data['end_time']);
        $data['begin_time'] = strtotime($data['begin_time']);
        $projects = Project::with('user', 'city')->whereBetween('created_at', [$data['begin_time'], $data['end_time']])->paginate(10);
        $return_date = array();
        $projects_data = array();
        foreach ($projects as $k => $v) {
            $projects_data[$k]['id'] = $v->id;
            $projects_data[$k]['subject'] = $v->subject;
            $projects_data[$k]['user'] = isset($v->user) ? isset($v->user->nickname) ? $v->user->nickname : $v->user->realname : '';
            $projects_data[$k]['project_period'] = $v->project_period ? $v->project_period : '';
            $projects_data[$k]['city'] = isset($v->city->name) ? $v->city->name : '';
            $projects_data[$k]['created_at'] = $v->created_at->toDateTimeString();
            $projects_data[$k]['views'] = $v->views;
            $projects_data[$k]['track_person'] = $v->track_person;
            if ($v->status == 0) {
                $projects_data[$k]['status'] = '禁用';
            } elseif ($v->status == 1) {
                $projects_data[$k]['status'] = '正常';
            } elseif ($v->status == 2) {
                $projects_data[$k]['status'] = '不通过';
            }
            $projects_data[$k]['recommend'] = $v->recommend ? '推荐' : '暂不推荐';
        }
//        dd($projects_data);
        $return_date['list'] = $projects_data;
        $return_date['page'] = $projects->render(true);

        return AjaxCallbackMessage($return_date, true);
    }

    public function postQuery(Request $request)
    {
        $data = $request->input();

        $data['end_time'] = strtotime($data['end_time']);
        $data['begin_time'] = strtotime($data['begin_time']);
//        dd($data);

        if ('pub' == $data['type']) {
            $datas = Project::with('user', 'city', 'zone')->whereBetween('created_at', [$data['begin_time'], $data['end_time']])->where('status', '!=', -1)->paginate(10);

            $return_date = array();
            $projects_data = array();
            foreach ($datas as $k => $v) {
                $projects_data[$k]['id'] = $v->id;
                //项目名称
                '' != $v->subject ? $projects_data[$k]['subject'] = cut_str($v->subject, 10) : $projects_data[$k]['subject'] = '';
                //地区
                if (isset($v->zone)) {
                    $projects_data[$k]['zone'] = $v->zone->name;
                } else {
                    $projects_data[$k]['zone'] = '';
                }

                //发布时间
                $projects_data[$k]['created_at'] = $v->created_at->toDateTimeString('Y-m-d');

                //类型
                if ($v->type == 'chuangye') {
                    $projects_data[$k]['type'] = '创业';
                } elseif ($v->type == 'newthree') {
                    $projects_data[$k]['type'] = '新三板';
                } else {
                    $projects_data[$k]['type'] = '';
                }
            }
        } elseif ('show_apply' == $data['type']) {
            $datas = RoadshowApply::with('maker', 'user', 'project')
                ->whereBetween('created_at', [$data['begin_time'], $data['end_time']])->paginate(10);
            $return_date = array();
            $projects_data = array();
            foreach ($datas as $k => $v) {
                //申请人
                if ($v->user->nickname) {
                    $projects_data[$k]['username'] = $v->user->nickname;
                } elseif ($v->user->realname) {
                    $projects_data[$k]['username'] = $v->user->realname;
                } else {
                    $projects_data[$k]['username'] = $v->user->username;
                }
                //空间名
                isset($v->maker->name) ? $projects_data[$k]['maker_name'] = $v->maker->name : $projects_data[$k]['maker_name'] = '';

                //发起方
                if ($v->initiator == 'maker') {
                    $projects_data[$k]['initiator'] = '创客空间发起';
                } elseif ($v->initiator == 'project') {
                    $projects_data[$k]['initiator'] = '项目方发起';
                } else {
                    $projects_data[$k]['initiator'] = '';
                }

                //申请时间
                $projects_data[$k]['created_at'] = $v->created_at->toDateTimeString('Y-m-d');
            }
        } else {
            $datas = ActivityProject::with('activity', 'project')
                ->whereBetween('created_at', [$data['begin_time'], $data['end_time']])->paginate(10);
            $return_date = array();
            $projects_data = array();
            foreach ($datas as $k => $v) {
                //项目名
                isset($v->project->subject) ? $projects_data[$k]['project_name'] = $v->project->subject : $projects_data[$k]['project_name'] = '';
                //活动名
                isset($v->activity->subject) ? $projects_data[$k]['activity_name'] = $v->activity->subject : $projects_data[$k]['activity_name'] = '';
                //申请时间
                $projects_data[$k]['created_at'] = $v->created_at->toDateTimeString('Y-m-d');
            }
        }

        $return_date['list'] = $projects_data;
        $return_date['page'] = $datas->render(true);
        $return_date['type'] = $data['type'];

        return AjaxCallbackMessage($return_date, true);
    }

    /**
     * 以Excel表格形式导出数据
     *
     */
    public function getExport(Request $request)
    {
        $data = $request->input();
        if (!$data['type'] || $data['type'] == '') {
            return $this->tip('操作错误，请选择类型', url('projectstatistic/query'), false);
        }

        if (!$data['begin_time'] || $data['begin_time'] == '') {
            return $this->tip('操作错误，请选择开始时间', url('projectstatistic/query'), false);
        }

        if (!$data['end_time'] || $data['end_time'] == '') {
            return $this->tip('操作错误，请选择结束时间', url('projectstatistic/query'), false);
        }

        $data['end_time'] = strtotime($data['end_time']);
        $data['begin_time'] = strtotime($data['begin_time']);

        if ('pub' == $data['type']) {
            $datas = Project::with('user', 'city', 'zone')->whereBetween('created_at', [$data['begin_time'], $data['end_time']])
                ->where('status', '!=', -1)->get();
//        dd($articles);

            $title = [
                [
                    "nickname" => '项目名称',
                    "realname" => '地区',
                    "username" => '发布时间',
                    "source"   => '类型'
                ],
            ];

            $return_data = array();
            foreach ($datas as $k => $v) {
                //项目名称
                '' != $v->subject ? $return_data[$k]['subject'] = cut_str($v->subject, 10) : $return_data[$k]['subject'] = '';
                //地区
                if (isset($v->zone)) {
                    $return_data[$k]['zone'] = $v->zone->name;
                } else {
                    $return_data[$k]['zone'] = '';
                }

                //发布时间
                $return_data[$k]['created_at'] = $v->created_at->toDateTimeString('Y-m-d');

                //类型
                if ($v->type == 'chuangye') {
                    $return_data[$k]['type'] = '创业';
                } elseif ($v->type == 'newthree') {
                    $return_data[$k]['type'] = '新三板';
                } else {
                    $return_data[$k]['type'] = '';
                }
            }
            $pubs_info = array_merge($title, $return_data);
            Excel::create(
                '项目发布列表',
                function ($excel) use ($pubs_info) {
                    $excel->sheet(
                        '项目发布列表',
                        function ($sheet) use ($pubs_info) {
                            $sheet->rows($pubs_info);
                        }
                    );
                }
            )->export('xls');
        } elseif ('show_apply' == $data['type']) {
            $datas = RoadshowApply::with('maker', 'user', 'project')
                ->whereBetween('created_at', [$data['begin_time'], $data['end_time']])->get();

            $title = [
                [
                    "username"   => '申请人',
                    "initiator"  => '发起类型',
                    "maker_name" => '空间名',
                    "created_at" => '申请时间'
                ],
            ];

            $return_data = array();

            foreach ($datas as $k => $v) {
                //申请人
                if ($v->user->nickname) {
                    $return_data[$k]['username'] = $v->user->nickname;
                } elseif ($v->user->realname) {
                    $return_data[$k]['username'] = $v->user->realname;
                } else {
                    $return_data[$k]['username'] = $v->user->username;
                }
                //空间名
                isset($v->maker->name) ? $return_data[$k]['maker_name'] = $v->maker->name : $return_data[$k]['maker_name'] = '';

                //发起方
                if ($v->initiator == 'maker') {
                    $return_data[$k]['initiator'] = '创客空间发起';
                } elseif ($v->initiator == 'project') {
                    $return_data[$k]['initiator'] = '项目方发起';
                } else {
                    $return_data[$k]['initiator'] = '';
                }

                //申请时间
                $return_data[$k]['created_at'] = $v->created_at->toDateTimeString('Y-m-d');
            }

            $apply_info = array_merge($title, $return_data);
            Excel::create(
                '项目路演申请列表',
                function ($excel) use ($apply_info) {
                    $excel->sheet(
                        '项目路演申请列表',
                        function ($sheet) use ($apply_info) {
                            $sheet->rows($apply_info);
                        }
                    );
                }
            )->export('xls');
        } else {
            $datas = ActivityProject::with('activity', 'project')
                ->whereBetween('created_at', [$data['begin_time'], $data['end_time']])->get();

            $title = [
                [
                    "nickname" => '项目名',
                    "realname" => '活动名',
                    "username" => '路演时间'
                ],
            ];

            $return_data = array();
            foreach ($datas as $k => $v) {
                //项目名
                isset($v->project->subject) ? $return_data[$k]['project_name'] = $v->project->subject : $return_data[$k]['project_name'] = '';
                //活动名
                isset($v->activity->subject) ? $return_data[$k]['activity_name'] = $v->activity->subject : $return_data[$k]['activity_name'] = '';
                //申请时间
                $return_data[$k]['created_at'] = $v->created_at->toDateTimeString('Y-m-d');
            }

            $suc_info = array_merge($title, $return_data);
            Excel::create(
                '路演成功列表',
                function ($excel) use ($suc_info) {
                    $excel->sheet(
                        '路演成功列表',
                        function ($sheet) use ($suc_info) {
                            $sheet->rows($suc_info);
                        }
                    );
                }
            )->export('xls');
        }
    }
}